const Controller = require('egg').Controller;

class MessageController extends Controller {
  // 发送消息
  async send() {
    const { ctx, service } = this;
    
    try {
      // 参数验证
      const rules = {
        receiver_id: { type: 'number', required: true },
        content: { type: 'string', required: false },
        message_type: { type: 'string', required: false },
        image_url: { type: 'string', required: false },
        file_url: { type: 'string', required: false }
      };
      ctx.validate(rules);
      
      const messageData = ctx.request.body;
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      messageData.sender_id = decode.user_id;
      messageData.receiver_id = parseInt(messageData.receiver_id);
      
      // 验证消息内容
      if (!messageData.content && !messageData.image_url && !messageData.file_url) {
        throw new Error('消息内容不能为空');
      }
      
      const message = await service.message.sendMessage(messageData);
      
      ctx.body = {
        code: 0,
        data: message,
        msg: '发送消息成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '发送消息失败'
      };
    }
  }
  
  // 获取会话的消息列表
  async list() {
    const { ctx, service } = this;
    
    try {
      const { conversation_id } = ctx.params;
      
      // URL参数是字符串，转换为数字
      const conversationId = parseInt(conversation_id);
      
      if (isNaN(conversationId)) {
        throw new Error('会话ID格式错误');
      }
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const result = await service.message.getConversationMessages(conversationId, userId, ctx.query);
      
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取消息列表成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '获取消息列表失败'
      };
    }
  }
  
  // 标记消息为已读
  async markAsRead() {
    const { ctx, service } = this;
    
    try {
      // 参数验证
      const rules = {
        message_ids: { type: 'array', required: true }
      };
      ctx.validate(rules);
      
      const { message_ids } = ctx.request.body;
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const result = await service.message.markAsRead(message_ids, userId);
      
      ctx.body = {
        code: 0,
        data: result,
        msg: '标记消息为已读成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '标记消息为已读失败'
      };
    }
  }
  
  // 删除消息
  async delete() {
    const { ctx, service } = this;
    
    try {
      const { id } = ctx.params;
      
      // URL参数是字符串，转换为数字
      const messageId = parseInt(id);
      
      if (isNaN(messageId)) {
        throw new Error('消息ID格式错误');
      }
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      await service.message.deleteMessage(messageId, userId);
      
      ctx.body = {
        code: 0,
        data: null,
        msg: '删除消息成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '删除消息失败'
      };
    }
  }
  
  // 获取未读消息总数
  async unreadCount() {
    const { ctx, service } = this;
    
    try {
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const count = await service.message.getUnreadCount(userId);
      
      ctx.body = {
        code: 0,
        data: { count },
        msg: '获取未读消息总数成功'
      };
    } catch (error) {
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '获取未读消息总数失败'
      };
    }
  }
}

module.exports = MessageController;